const express = require('express')
const router = express.Router()
const { curriculum } = require('../../models/curriculum')

// 获取所有课程列表
router.get('/', (req, res) => {
    curriculum.find().then(result => {
        res.json({
            status: 200,
            data: result.map(item => {
                return {
                    id: item._id,
                    name: item.name,
                    start_time: item.start_time,
                    end_time: item.end_time,
                    createdDate: item.createdDate
                }
            })
        })
    })
})

// 根据id获取课程
router.get('/:id', (req, res) => {
    curriculum.findOne({ _id: req.params.id }).then(result => {
        res.json({
            status: 200,
            data: result
        })
    })
})

// 获取该老师下面所有的课程
router.get('/teacher/:id', (req, res) => {
    curriculum.find({ teacherId: req.params.id }).then(result => {
        res.json({
            status: 200,
            data: result
        })
    })
})

// 添加课程
router.post('/', (req, res) => {
    const { name, start_time, end_time } = req.body
    curriculum.findOne({ name, start_time, end_time }).then(result => {
        if (result) return res.json({
            code: 400,
            msg: '该上课时间的课程已存在'
        })

        const data = new curriculum({
            name,
            start_time,
            end_time
        })

        data.save().then(() => res.json({
            code: 200,
            msg: '添加成功'
        }))
    })
})

// 修改课程信息
router.put('/', (req, res) => {
    const { id, name, start_time, end_time } = req.body
    const _id = id,
        $set = {
            name: name ? name : '',
            start_time: start_time ? start_time : '',
            end_time: end_time ? end_time : ''
        }
    curriculum.findOneAndUpdate({ _id }, { $set }, { new: true }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '修改成功'
        })
    }).catch(error => {
        res.status(500).json({
            code: 500,
            msg: '修改失败'
        })
    })
})

// 删除课程
router.delete('/', (req, res) => {
    curriculum.findOneAndRemove({ _id: req.body.id }).then(() => {
        res.status(200).json({
            code: 200,
            msg: '删除成功'
        })
    })
})


module.exports = router